<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="比赛时间" prop="postCode">
        <!-- <el-input
          v-model="queryParams.postCode"
          placeholder="请输入比赛时间"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <el-date-picker
                type="month"
                v-model="queryParams.postCode"
                format="yyyy.MM"
                value-format="yyyy.MM"
                :style="{ width: '100%' }"
                placeholder="请输入获奖日期"
                clearable
              >
              </el-date-picker>
      </el-form-item>
      <el-form-item label="比赛名称" prop="postName">
        <el-input
          v-model="queryParams.postName"
          placeholder="请输入比赛名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="奖项" prop="status">
        <el-select v-model="queryParams.status" placeholder="奖项" clearable>
          <el-option
            v-for="(kind, index) in kinds"
            :key="index"
            :label="kind"
            :value="kind"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:post:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:post:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:post:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:post:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="获奖日期" align="center" prop="game_time" />
      <el-table-column label="赛事名称" align="center" prop="game_name" />
      <el-table-column label="比赛结果" align="center" prop="game_result" />
      <el-table-column label="top" align="center" prop="top" />
      <el-table-column label="竞赛成员" align="center" prop="name" />
      <el-table-column label="证书" align="center" prop="certificate" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:post:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:post:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-row :gutter="15">
        <el-form
          ref="elForm"
          :model="formData"
          :rules="rules"
          size="medium"
          label-width="100px"
        >
          <el-col :span="15">
            <el-form-item label="获奖日期" prop="game_time">
              <el-date-picker
                type="month"
                v-model="formData.game_time"
                format="yyyy.MM"
                value-format="yyyy.MM"
                :style="{ width: '100%' }"
                placeholder="请选择获奖日期"
                clearable
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="15">
            <el-form-item label="比赛名称" prop="game_name">
              <el-input
                v-model="formData.game_name"
                placeholder="请输入比赛名称"
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="15">
            <el-form-item label="比赛结果" prop="game_result">
              <el-input
                v-model="formData.game_result"
                placeholder="请输入比赛结果"
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="15">
            <el-form-item label="Top" prop="top">
              <el-input
                v-model="formData.top"
                placeholder="请输入Top(可选)"
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="15">
            <el-form-item label="比赛成员" prop="name">
              <el-input
                v-model="formData.name"
                show-word-limit
                readonly
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="选择成员">
              <el-input
                v-model="searchName"
                placeholder="请输入选择成员"
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <el-form-item label="" prop="field101">
              <el-button type="primary" @click="searchUser">搜索</el-button>
            </el-form-item>
          </el-col>

          <!-- 搜索结果区域 -->
          <el-col :span="24">
            <div class="search-results">
              <el-table
                :data="searchResults"
                style="width: 100%"
                @row-click="handleRowClick"
              >
                <!-- 表格列定义 -->
                <el-table-column
                  prop="member_id"
                  label="ID"
                  width="180"
                ></el-table-column>
                <el-table-column
                  prop="name"
                  label="Name"
                  width="180"
                ></el-table-column>
              </el-table>
            </div>
          </el-col>

          <el-col :span="15">
            <el-form-item label="证书上传" prop="certificate">
              <el-upload
                ref="certificate"
                :file-list="certificatefileList"
                :auto-upload="false"
                :before-upload="certificateBeforeUpload"
                list-type="picture"
                :data="picData"
                :limit="1"
                action="'https://jsonplaceholder.typicode.com/posts/',"
              >
                <el-button size="small" type="primary" icon="el-icon-upload"
                  >点击上传</el-button
                >
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <div >
              <img :src="picData.certificate" alt="" style="width: 200px; height:140px">
            </div>
          </el-col>

        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPost,
  searchUser,
  delPost,
  addPost,
  updatePost,
  uploadFile,
} from "@/api/system/competition";

export default {
  name: "Post",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      isNameCleared: false, // 添加这个标志
      // 上传图片时的参数
      picData: {
        game_id: "",
        certificate:'',
      },
      // 查询成员结果
      searchResults: [],

      searchName: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 竞赛表格数据
      postList: [],
      //  奖项种类选择框
      kinds: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        postCode: undefined,
        postName: undefined,
        status: undefined,
      },
      // 表单参数
      formData: {
        game_time: "",
        game_name: "",
        game_result: "",
        top: "",
        name: "",
        team: [],
      },
      certificatefileList: [],
      // 表单校验
      rules: {
        game_time: [
          {
            required: true,
            message: "请选择获奖日期",
            trigger: "blur",
          },
          {
            pattern: /^(2[0-9]{3}).(0[1-9]|1[0-2])$/, // 正则表达式：yyyy-MM
            message: "日期格式应为 yyyy-MM",
            trigger: "change",
          },
        ],
        game_name: [
          {
            required: true,
            message: "请输入比赛名称",
            trigger: "blur",
          },
        ],
        game_result: [
          {
            required: true,
            message: "请输入比赛结果",
            trigger: "blur",
          },
        ],
        top: [
          {
            required: false,
            trigger: "blur",
          },
          {
            pattern: /^\d+$/,
            message: "top格式应为数字",
            trigger: "change",
          },
        ],
        team: [
          {
            required: true,
            message: "请输入选择成员",
            trigger: "blur",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入选择成员",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    submitPic() {
      const file = this.$refs.certificate.uploadFiles[0];
      // 检查文件是否存在
      if (!file || !file.raw) {
        this.$modal.error("请选择要上传的文件");
        return;
      }
      const formData = new FormData();
      formData.append("file", file.raw);
      formData.append("game_id", this.picData.game_id);
      formData.append("certificate", this.picData.certificate);
      // 其他自定义参数

      uploadFile(formData)
        .then((response) => {
          if (response.code == 200) {
            this.$modal.msgSuccess("新增成功");
          } else {
            this.$modal.error("上传错误");
          }
        })
        .catch((error) => {
          console.error("出错了" + error);
        });
    },

    // 搜索队员模块
    handleRowClick(row) {
      if (!this.isNameCleared) {
        this.formData.name = "";
        this.isNameCleared = true; // 设置标志，表示已经清空过 name
      }

      // 检查 formData.team 是否存在并且是一个数组
      if (!Array.isArray(this.formData.team)) {
        this.formData.team = []; // 如果 team 不是数组，则初始化为空数组
      }
      // 将id加入数组
      // 检查是否已经包含该id
      if (!this.formData.team.includes(row.member_id)) {
        this.formData.team.push(row.member_id);
      }

      // 直接使用 row.name 更新 formData.name
      if (!this.formData.name) {
        this.formData.name = row.name;
      } else {
        if (!this.formData.name.includes(row.name)) {
          this.formData.name += "、" + row.name;
        }
      }
      console.log("Updated formData.team:", this.formData.team);
      console.log("Updated formData.name:", this.formData.name);
    },
    // 查找组员
    searchUser() {
      searchUser(this.searchName).then((res) => {
        console.log(res);
        this.searchResults = res.data;
      });
    },

    certificateBeforeUpload(file) {
      const isImage = file.type.startsWith("image/");
      const isLt80M = file.size / 1024 / 1024 < 80; // 限制文件大小为 80MB

      if (!isImage) {
        this.$message.error("上传的文件必须是图片格式!");
      }

      if (!isLt80M) {
        this.$message.error("上传的图片大小不能超过 80MB!");
      }

      if (this.certificatefileList.length >= 1) {
        this.$message.error("只允许上传一张图片!");
        return false; // 阻止上传
      }

      if (isImage && isLt80M) {
        // 将文件添加到文件列表中
        this.certificatefileList.push({
          name: file.name,
          url: URL.createObjectURL(file),
        });
      }

      return isImage && isLt80M;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listPost(this.queryParams).then((response) => {
        this.postList = response.data.competitions;
        this.kinds = response.data.kinds;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.formData = {
        game_time: "",
        game_name: "",
        game_result: "",
        top: "",
        name: "",
        certificate: "",
        team: [],
      };
      this.certificatefileList = [];
      this.searchResults = [];
      this.searchName = "";
      this.picData.game_id = "";
      this.picData.certificate = "";
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.postId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(row);
      this.reset();
      this.formData = row;
      this.searchResults = [];
      this.open = true;
      // 点击修改按钮时，将game_id赋值，方便更新证书
      this.picData.game_id = row.game_id;
      this.picData.certificate = row.certificate
      this.isNameCleared = false;
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["elForm"].validate((valid) => {
        if (valid) {
          if (this.formData.game_id != undefined) {
            // 这是修改
            updatePost(this.formData).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("修改成功");
                this.submitPic();
                this.open = false;
                this.getList();
              } else {
                this.$modal.error("上传错误");
              }
            });
          } else {
            // 这是提交
            addPost(this.formData).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("新增成功");
                this.picData.game_id = response.game_id;
                this.picData.certificate = '';
                this.open = false;
                this.submitPic();
                this.getList();
              } else {
                this.$modal.error("上传错误");
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const game_id = row.game_id;
      this.$modal
        .confirm('是否确认删除成员编号为"' + game_id + '"的数据项？')
        .then(function () {
          return delPost(game_id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/post/export",
        {
          ...this.queryParams,
        },
        `post_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
